package com.yinda.dt.produce.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;

import com.yinda.dt.produce.R;


/**
 * 带字符限制输入的EditText
 * <br/>
 * Created by 小灿 on 2016/7/29.
 */
@SuppressLint("AppCompatCustomView")
public class SupportEditText extends EditText {

    private int maxWordCount;

    public SupportEditText(Context context) {
        super(context);
    }

    public SupportEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.SupportEditText);

        maxWordCount = typedArray.getInteger(
                R.styleable.SupportEditText_maxWordCount, 30);

        typedArray.recycle();

        setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    setError(null);
                }
            }
        });

        addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int len = s.toString().trim().length();
                if (len > maxWordCount) {
                    setError("最多输入" + maxWordCount + "个字");
                    setText(s.toString().substring(0, maxWordCount));
                    setSelection(maxWordCount);
                }
            }
        });
    }

    public void setMaxWordCount(int maxWordCount) {
        this.maxWordCount = maxWordCount;
    }
}
